package com.sxygsj.baselibrary.network

import android.util.Log
import com.sxygsj.baselibrary.network.netException.DataResultException

import okhttp3.ResponseBody

import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.nio.charset.Charset
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * @Author LD
 * @Time 2021/2/26 17:06
 * @Describe 通用的简化回调的操作(属于顶层方法，静态方法)
 * @Modify
 */

suspend fun <T> Call<T>.await(): T {

    return suspendCoroutine { continuation ->
        enqueue(object : Callback<T> {
            override fun onResponse(call: Call<T>, response: Response<T>) {
                val body = response.body()
                Log.i("ceshi", "onResponse: await()里code为：" + response.code())
                if (body != null) {

                    //实际这里还会出现没有解析全部是json字符串，但是请求错误的情况
                    if (body is ResponseBody) {
                        var mBody = body as ResponseBody
                        //不能这样使用，因为它会导致response关闭，就算是resume(body)，其实这里已经为空了
//                        var str = mBody.string()
                        var source=mBody.source()
                        var str = source.buffer().clone().readString(Charset.forName("UTF-8"))

                        var jsonObject = JSONObject(str)
                        var code = jsonObject.get("code")
                        when (code) {
                            "100" -> {
                                Log.i("ceshi", "onResponse:(一般的ResponseBody)请求成功 ")
                                continuation.resume(body)
                            }
                            "2001" -> {
                                Log.i("ceshi", "onResponse: 未登录(一般的ResponseBody)，跳转到登录界面")
                            }
                            else -> {
                                continuation.resumeWithException(RuntimeException("访问错误:$code"))
                            }
                        }
                    } else {
                        Log.i("ceshi", "onResponse:(具体的类型解析)请求成功 ")
                        continuation.resume(body)
                    }
                } else{
                    continuation.resumeWithException(RuntimeException("response body is null"))
                }
            }

            override fun onFailure(call: Call<T>, t: Throwable) {

                if (t is DataResultException) {
                    if (t.code == 2001) {// xuyaogai
                        Log.i("ceshi", "onResponse: 未登录(具体的解析)，跳转到登录界面")
                    } else {
                        continuation.resumeWithException(t)
                    }
                } else {
                    continuation.resumeWithException(t)
                }

            }
        })
    }
}
